package com.hnjmxy.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FileReaderServlet
 */
@WebServlet("/FileReaderServlet")
public class FileReaderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       List<String> words = new ArrayList<String>();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileReaderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		//获取文件的绝对路径
		String path = this.getServletContext().getRealPath("WEB-INF/new_words.txt");
		try {
			BufferedReader br = new BufferedReader(new FileReader(path));
			String line;
			while((line=br.readLine())!=null) {
				words.add(line);//把读的一行数据放置到集合中
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		response.getWriter().append("Served at: ").append(request.getContextPath());
		PrintWriter out = response.getWriter();
		for(String s:words) {
			out.write(s);
		}
		//在服务器上创建一个upload文件夹
		String path = this.getServletContext().getRealPath("/upload");
		File f =new File(path);//文件或目录
		if(!f.exists()) {//如果目录不存在
			f.mkdir();
		}
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
